import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:crypto/crypto.dart';
// import 'package:crypto/crypto.dart';

class DGGRequestSign {
  static String? sysCode;
  static String? sysKey;

  ///最终GET请求生成请求Header
  static Map<String, dynamic> generateGetHeader(Map data, Map headers) {
    assert((null != sysCode && '' != sysCode) ? true : false, 'syscode为空');
    assert((null != sysKey && '' != sysKey) ? true : false, 'syskey为空');
    String requestParams = DGGRequestSign.sortFormatParams(data);
    var timestamp = new DateTime.now().millisecondsSinceEpoch;
    var nonce = getNonce(10);
    var sinParams = {
      'nonce': nonce,
      'time': timestamp,
      'data': requestParams,
    };
    String signParmStr = DGGRequestSign.sortFormatParams(sinParams);
    String sign = DGGRequestSign.createSign(signParmStr);
    String platform = 'APP';
    if (Platform.isAndroid) {
      platform = 'ANDROID';
    } else {
      platform = 'IOS';
    }
    // var userId = Provider.of<GlobalProvider>(context).userInfo.userId ?? '';
    //var userToken = Provider.of<GlobalProvider>(context).userInfo.tokenId ?? '';
    //生成验签必须请求头
    var addHeader = {
      'nonce': nonce,
      'time': timestamp,
      'sign': sign,
      'sysCode': sysCode,
      'X-Req-Client': platform
    };
    //添加自定义请求头
    if (headers.isNotEmpty) {
      headers.forEach((key, value) {
        addHeader.addAll({key: value});
      });
    }
    //'X-Req-YT': 'BUS_YT_CY',
    //'X-Auth-Token': userToken ?? '',
    // 'X-Req-UserId': userId ?? ''
    return addHeader;
  }

  ///最终POST请求生成请求Header
  static Map<String, dynamic> generatePostHeader(Map data, Map headers) {
    assert((null != sysCode && '' != sysCode) ? true : false, 'syscode为空');
    assert((null != sysKey && '' != sysKey) ? true : false, 'syskey为空');
    String requestParams = '';
    if (data != null) {
      try {
        requestParams = json.encode(data);
      } catch (e) {
        print('参数转换异常${e.toString()}');
      }
    }
    var timestamp = new DateTime.now().millisecondsSinceEpoch;
    var nonce = getNonce(10);
    var sinParams = {
      'nonce': nonce,
      'time': timestamp,
      'data': requestParams,
    };
    String signParmStr = DGGRequestSign.sortFormatParams(sinParams);
    String sign = DGGRequestSign.createSign(signParmStr);
    String platform = 'APP';
    if (Platform.isAndroid) {
      platform = 'ANDROID';
    } else {
      platform = 'IOS';
    }
    // var userId = Provider.of<GlobalProvider>(context).userInfo.userId ?? '';
    //var userToken = Provider.of<GlobalProvider>(context).userInfo.tokenId ?? '';
    //生成验签必须请求头
    var addHeader = {
      'nonce': nonce,
      'time': timestamp,
      'sign': sign,
      'sysCode': sysCode,
      'X-Req-Client': platform
    };
    //添加自定义请求头
    if (headers.isNotEmpty) {
      headers.forEach((key, value) {
        addHeader.addAll({key: value});
      });
    }
    //'X-Req-YT': 'BUS_YT_CY',
    // 'X-Req-UserId': userId ?? '',
    //'X-Auth-Token': userToken ?? ''
    return addHeader;
  }

  ///排序拼接字符串
  static String sortFormatParams(Map params) {
    String resultStr = '';
    if (params.isNotEmpty) {
      List newKeys = [];
      params.forEach((key, value) {
        newKeys.add(key);
      });
      newKeys.sort();
      Map newObj = {};
      for (var i = 0; i < newKeys.length; i++) {
        newObj[newKeys[i]] = params[newKeys[i]];
      }
      newObj.forEach((key, value) {
        if (value != null && value != '') {
          resultStr = '$resultStr$key=$value&';
          //resultStr + key + '=' + newObj[key] + '&';
        }
      });
      if (resultStr.length > 0) {
        resultStr = resultStr.substring(0, resultStr.length - 1);
      }
    } else {}
    return resultStr;
  }

  ///追加签名私钥
  static String appendSignParams(String sortFromatStr) {
    return '$sortFromatStr&sysCode=$sysCode&secret=$sysKey';
  }

  ///签名
  static String createSign(String signParamStr) {
    String appendStr = appendSignParams(signParamStr);
    var content = new Utf8Encoder().convert(appendStr);
    var digest = md5.convert(content);
    return digest.toString().toUpperCase();
  }

  ///获取随机字符串
  static String getNonce(int length) {
    var timestamp = DateTime.now().millisecondsSinceEpoch + 1;
    String scopeF = '123456789'; //首位
    String scopeC = '0123456789'; //中间
    String result = '';
    for (int i = 0; i < length; i++) {
      if (i == 1) {
        result = scopeF[Random().nextInt(scopeF.length)];
      } else {
        result = result + scopeC[Random().nextInt(scopeC.length)];
      }
    }
    String nonce = '$timestamp$result';
    return nonce;
  }

  ///根据请求URL解析请求参数
  static Map requestParamsWithURL(String url) {
    if (url.isNotEmpty) {
      if (url.indexOf('?') != -1) {
        String paramStr = url.split('?').last;
        var paramArray = paramStr.split('&');
        var resultParams = {};
        for (var param in paramArray) {
          var keyValues = param.split('=');
          if (keyValues.length > 0) {
            var key = keyValues.first;
            if (keyValues.length > 1) {
              var value = keyValues.last;
              resultParams[key] = value;
            }
          }
        }
        return resultParams;
      } else {
        return {};
      }
    } else {
      return {};
    }
  }
}
